import logging
from apscheduler.triggers.cron import CronTrigger
from apscheduler.schedulers.background import BackgroundScheduler
from django_apscheduler.jobstores import DjangoJobStore
from .models import taskAPS
logger = logging.getLogger('mylogger')
skipJob = ["MonJob"]

def monJob():
    for i in taskAPS.objects.all():
        logger.info(f"自定义 JOB {i.JOB_ID} 状态 -- {i.Cron_STATUS}")
        if bool(i.Cron_STATUS):
            try:
                job = scheduler.get_job(i.JOB_ID)
                logger.info(f"自定义 JOB {i.JOB_ID} 状态正常")
            except Exception:
                logger.warning(f"自定义 JOB {i.JOB_ID} 状态异常，执行同步操作 status --> True --> begin")
                scheduler.add_job(i.JOB_ID,i.Cron_TIME)
                logger.warning(f"自定义 JOB {i.JOB_ID} 状态异常，执行同步操作 status --> True --> end")



scheduler = BackgroundScheduler()
scheduler.add_jobstore(DjangoJobStore(), 'default')

scheduler.add_job(monJob,CronTrigger.from_crontab("* * * * *", timezone="Asia/Shanghai"), id="MonJob",
                      replace_existing=True, args=[])

scheduler.start()



